var driver = require('./db');
var async = require('async');
var fs = require('fs');
var utils = require('./utils');

var insertDB = function (data, _default) {

    var url = "mongodb://localhost:27017/job";
    var table = "job";

    // var url = "mongodb://47.104.130.19:27017/knx_posts_db";
    // var table = "offical_posts_coll";


    var _query = { "name": data['name'],"url":data['url'],"company":data["company"] };

    data['stime'] = new Date();

    async.waterfall([
        // 连接数据库        
        function (callback) {
            driver.connect(callback, url);
        },
        // 查找
        function (db, callback) {
            driver.find(db, callback, table, _query);
            // driver.insert(db, callback, table, data);
        },
        // 
        function (db, res, callback) {
            // 未找到记录
            if (res.success && res.data.length == 0) {
               
                driver.insert(db, callback, table, data);
            } else {
                // file(data);
                // 已存在数据库
                console.log('已存在数据库');
                driver.update(db, callback, table, _query, {$set:data});          

            }
        },
        function (db, res, callback) {
            driver.close(db, res, callback);
        }
    ],
        // result
        function (err, result) {
            // console.log("resulte");

            if (err) {
                console.log(err);
                return;
            }else{
                // console.log('success');
            }

            // console.log('find a new one '+data['title']+data['href']);

            // _default.successHandel(_default);
        }
    );
};

module.exports = insertDB;


var file = function (data) {
    var filename = __dirname + "/repeat.json";
    // 序列化
    var destString = JSON.stringify(data);

    fs.appendFile(filename, destString, 'utf8', (err) => {
        if (err) throw err;
        console.log('The "data to append" was appended to file!');
    });
}